package indi.mozping;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author by mozping
 * @Classname ZkClientHello
 * @Description 使用zkClient操作zookeeper
 * @Date 2019/4/20 17:04
 */
public class ZkClientHello {

    private final static String CONNECT_STRING = "192.168.13.53:2181";
    private static final String PATH = "/node1/node2/node3";
    private static final String PATH_PREFIX = "/node1";
    private static final String VALUE = "123";
    private static final Logger LOG = LoggerFactory.getLogger(ZkClientHello.class);

    private static ZkClient getInstance() {
        return new ZkClient(CONNECT_STRING, 5000);
    }

    public static void main(String[] args) throws InterruptedException {
        ZkClient zkClient = getInstance();
        //1.创建持久节点；zkclient 提供递归创建父节点的功能
        LOG.info("准备创建节点...");
        zkClient.createPersistent(PATH, true);
        TimeUnit.SECONDS.sleep(2);

        //2.获取子节点
        LOG.info("准备获取子节点...");
        List<String> list = zkClient.getChildren(PATH_PREFIX);
        for (String nodeName : list) {
            LOG.info(nodeName);
        }
        TimeUnit.SECONDS.sleep(2);

        //3.修改节点值
        LOG.info("准备修改节点...");
        //注册监听器，监听数据变化
        zkClient.subscribeDataChanges(PATH_PREFIX, new IZkDataListener() {

            public void handleDataChange(String s, Object o) throws Exception {
                LOG.info("节点名称：" + s + "->节点修改后的值 " + o);
            }

            public void handleDataDeleted(String s) throws Exception {
                LOG.info("handleDataDeleted" + s);
            }
        });
        zkClient.writeData(PATH_PREFIX, VALUE);
        TimeUnit.SECONDS.sleep(2);


        //2.删除节点；可以递归删除
        LOG.info("准备递归删除节点...");
        //注册监听器，监听子节点变化
        zkClient.subscribeChildChanges(PATH_PREFIX, new IZkChildListener() {
            public void handleChildChange(String s, List<String> list) throws Exception {
                LOG.info("节点名称：" + s + "->" + "当前的节点列表：" + list);
            }
        });
        zkClient.deleteRecursive(PATH_PREFIX);
    }
}
